package com.fzrskj.cloud.free.user.service;

import com.alibaba.fastjson.JSON;
import com.fzrskj.cloud.free.common.bean.ValidResult;
import com.fzrskj.cloud.free.consts.AppCode;
import com.fzrskj.cloud.free.consts.CConsts;
import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.enums.UserCertifyEnum;
import com.fzrskj.cloud.free.core.tool.*;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.EncryptUtils;
import com.fzrskj.cloud.free.core.utils.ProtectionStartUtils;
import com.fzrskj.cloud.free.core.utils.SessionUtils;
import com.fzrskj.cloud.free.dic.dao.DicParamDao;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.bean.Cookies;
import com.fzrskj.cloud.free.sys.bean.SendResult;
import com.fzrskj.cloud.free.sys.bean.User;
import com.fzrskj.cloud.free.sys.utils.CUserUtils;
import com.fzrskj.cloud.free.sys.utils.SendMailUtils;
import com.fzrskj.cloud.free.sys.utils.SendSMSUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountData;
import com.fzrskj.cloud.free.user.bean.UserAccount;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import com.fzrskj.cloud.free.user.utils.UserAccountDataUtils;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import com.winiis.component.common.utils.tool.CSysTool;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.support.Session;
import ms.core.tool.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class UserAccountService extends CObject{

	private String formatUserAccountView(UserAccountView uv){
		String regTime = CDateTimeTool.dateToDateTimeString(uv.getRegTime());
		String loginTime = CDateTimeTool.dateToDateTimeString(uv.getLoginTime());
		String ret = CJsonTool.beanToJson(uv);
		ret = CJsonTool.delNode(ret, "regTime");
		ret = CJsonTool.addNode(ret, "regTime", regTime);
		ret = CJsonTool.delNode(ret, "loginTime");
		ret = CJsonTool.addNode(ret, "loginTime", loginTime);
		ret = CJsonTool.delNode(ret, "passWord");
		ret = CJsonTool.delNode(ret, "randomCode");
		//ret = CJsonTool.delNode(ret, "agentApiPass");
		String status = uv.getStatus();
		if (CConsts.ACCOUNT_FROZEN.equals(status)) {
			ret = CJsonTool.addNode(ret, "statusName", "冻结");
		} else if (CConsts.ACCOUNT_NORMAL.equals(status)) {
			ret = CJsonTool.addNode(ret, "statusName", "正常");
		} else if (CConsts.ACCOUNT_NOT_ACTIVE.equals(status)) {
			ret = CJsonTool.addNode(ret, "statusName", "未激活");
		} else {
			ret = CJsonTool.addNode(ret, "statusName", "未知状态");
		}
		return ret;
	}

	//if current user has logined
	private static boolean logined(HttpServletRequest request, String sid){
		Session s = CSessionTool.getSessionCloud(sid);
		if (s==null) {
			return false;
		}

		int uid		   = CookieTool.getUid(request);
		String account = CookieTool.getAccount(request);
		String said    = CookieTool.getSAID(request);
 		if ((uid<=0) || (uid!=s.getUID()) || StrTool.isBlankStr(said)) {
			return false;
		}

		return said.equals(CEncryptTool.encodeSAID(sid, uid, account));
	}

	/**
	 * user login, can login with user id or account register email
	 * @param req
	 * @param resp
	 * @param p={"userName":"admin@126.com","password":"admin","checkcode":"xxx"}
	 * @param sid
	 * @return
	 */
	public String userLogin(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		if (logined(req,sid)){
			return XmlCodeParser.formatResultTips(true, SysErr.USER_RELOGIN);
		}

		String account  = CJsonTool.getStrValue(p, "userName", "");
		String password = CJsonTool.getStrValue(p, "password", "");
		String checkcode= CJsonTool.getStrValue(p, "checkcode", "");

		Session session = CSessionTool.getSessionCloud(sid);
		String ssncode = session.getCheckCode();
		DicParamDao dicParamDao = new DicParamDao();
		String supCodeLogin = dicParamDao.getParamValue(DicParamEnum.SUPPORT_CODE_LOGIN.getVal());
		if(!supCodeLogin.equals("1")){
			if (StrTool.isBlankStr(checkcode) || !checkcode.toLowerCase().equals(ssncode.toLowerCase())) {
				return XmlCodeParser.formatResultTips(false, SysErr.SYS_CHECKCODE_ERR);
			}
		}
		//解密密码
		password = EncryptUtils.decodePublic(password);
		if (StrTool.isBlankStr(password)) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		if (StrTool.isBlankStr(account)){
			this.log(p+"-->invalid login parameter");
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		String visitIp = HttpTool.getRequestRemoteIp(req);
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccount ua = uaUtils.userLogin(account, password, visitIp);
		String err  = uaUtils.getErrCode();
		if (ua==null){
			return XmlCodeParser.formatResultTips(false, err);
		}

		if (ua.getStatus().equals(CConsts.ACCOUNT_NORMAL)){
			//set user session,it contains: user record id\ user id\ account
			int uid = ua.getUserId();
			Session ssn = new Session();
			ssn.setId(ua.getId());
			ssn.setUID(uid);
			ssn.setUname(ua.getUserName());
			//set user account email
			UserAccountView v = uaUtils.queryUserAccountView(ua.getId());
			ssn.setData(v.toJsonString());
			ssn.setUtype(1);
			//TODO to fill user functions
			ssn.setFuncs("");
			CSessionTool.setLoginSessionCloud(sid, ssn);
			//set user cookie,it contains: account id\account
			Cookies cks = new Cookies();
			cks.setId(ua.getId());
			cks.setUid(uid);
			cks.setAccount(ua.getUserName());
			cks.setUname(ua.getUserName());
			cks.setSaid(CEncryptTool.encodeSAID(sid, uid, ua.getUserName()));
			CookieTool.setLoginCookie(resp, sid, cks);

			EncryptUtils.makeSession(resp, req);

			//自动修复分配客服和技术
			uaUtils.allotCrmAndCSST(uid);

			UserLogUtils.addLog("user.login", ua.getUserId(), "用户登录成功");
		}
		String data = CJsonTool.beanToJson(ua);
		data = CJsonTool.delNode(data, "passWord");
		data = CJsonTool.delNode(data, "regTime");
		data = CJsonTool.delNode(data, "randomCode");
		data = CJsonTool.addNode(data, "regTime", CDateTimeTool.dateToDateString(ua.getRegTime()));
		return XmlCodeParser.formatResultData(true, err, data);
	}

	/**user logout
	 * @param req
	 * @param resp
	 * @param p can be ignorance
	 * @param sid
	 * @return
	 */
	public String userLogout(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		if (!logined(req, sid)){
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_LOGIN);
		}

		CSessionTool.delSessionCloud(sid);
		CookieTool.clearLoginCookie(resp);
		return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
	}

	/**
	 * user account has logined?
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String logined(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		if (!logined(req, sid)){
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_LOGIN);
		}
		if (CloudContextUtils.getSession().getUtype() != 1) {
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_LOGIN);
		}

		String data = String.format("{\"uname\":\"%s\"}", CSessionTool.getAccountCloud(sid));
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
	}

	/**
	 * 查询会员是否已注册
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String isRegister(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");

		UserAccountUtils uaUtils=new UserAccountUtils();
		UserAccount ret = uaUtils.isRegister(userName);
		JSONObject result = new JSONObject();
		if (ret!=null) {
			result.put("code", "-1");
		} else {
			result.put("code", "0");
		}
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS,result.toString());
	}

	/**
	 * 查询会员是否已注册
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String isRegisterEmail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String email = CJsonTool.getStrValue(p, "Email", "");

		UserAccountUtils uaUtils=new UserAccountUtils();
		UserAccount ret = uaUtils.isRegisterEmail(email);
		JSONObject result = new JSONObject();
		if (ret!=null) {
			result.put("code", "-1");
		} else {
			result.put("code", "0");
		}
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, result.toString());
	}

	/**
	 * user register
	 * @param req
	 * @param resp
	 * @param p={"userName":"user name","email":"email address","mobile":"mobile no","password":"password","checkcode":"xxxx"}
	 * @param sid
	 * @return
	 */
	public String userRegister(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		JSONObject j = CVerificationTool.StringToJsonObjectCV(p);
//		ValidResult ret = CVerificationTool.verificationApi("registeraccount", j);
//		if(!ret.isSuccess()){
//			return XmlCodeParser.formatCustomTips(false, ret.getMsg());
//		}
		if(StrTool.isBlankStr(j.optString("userName"))){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "账号名称不能为空！");
		}
		if(StrTool.isBlankStr(j.optString("password"))){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "密码不能为空！");
		}
		DicParamDao dicParamDao = new DicParamDao();
		String regVerImg = dicParamDao.getParamValue(DicParamEnum.REG_VERIFY_IMAGE.getVal());
		Session session = CSessionTool.getSessionCloud(sid);
		String checkCode = session.getCheckCode();
		if (!"1".equals(regVerImg) && !j.optString("checkcode").toLowerCase().equals(checkCode.toLowerCase())) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_CHECKCODE_ERR,"图片验证码输入错误！");
		}
		if (!j.optString("verification").equals(SessionUtils.get(CConsts.CODE_LOGIN_SESSION_NAME))) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "验证码不正确");
		}
		UserAccountUtils uaUtils = new UserAccountUtils();
		int rid = uaUtils.userRegister(j.optString("userName"), j.optString("email"),
				j.optString("mobile"), j.optString("password"), j.optInt("userType"),true);
		//to refresh user account info for userId
		UserAccountView uv = null;
		if (rid>0) {
			uv = uaUtils.queryUserAccountView(rid);
		}
		String code = uaUtils.getErrCode();
		if ((rid<=0) || (uv==null)){
			return XmlCodeParser.formatResultTips(false, code, uaUtils.getMsg());
		}

		int uid = uv.getUserId();
		//自动分配客户和技术
		uaUtils.allotCrmAndCSST(uid);
//		SendResult mRet = SendMailUtils.sendActiveAccountMail(uid);
//
//		String jsRet = CJsonTool.beanToJson(mRet);
//		jsRet = CJsonTool.addNode(jsRet, "uid", uid);
//		if (mRet.getId() < 0){
//			return XmlCodeParser.formatCustomTips(false, mRet.getMsg(), jsRet);
//		}
//
//		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, jsRet);

		return  XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
	}

	/**
	 * 用户注册-新.
	 * @param req
	 * @param resp
	 * @param p 	{
	                userType: 0,
					userName: '',
					password: '',
					passwordConfirm: '',
					checkcode: '',
					verificationCodeMobile:'',
					verificationCodeMail:'',
					email: '',
					mobile: ''}
	 * @param sid
	 * @return
	 */
	public String userRegisterV2(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		Integer userType = JsonTool.getIntValue(p, "userType", -1);
		String userName = JsonTool.getStrValue(p, "userName", "");
		String password = JsonTool.getStrValue(p, "password", "");
		if (userType != 0 && userType != 1) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "请选择用户类型！");
		}
		if(StrTool.isBlankStr(userName)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "账号名称不能为空！");
		}
		if(StrTool.isBlankStr(password)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "密码不能为空！");
		}
		String mobile = JsonTool.getStrValue(p, "mobile", "");
		String verificationCodeMobile = JsonTool.getStrValue(p, "verificationCodeMobile", "");
		String email = JsonTool.getStrValue(p, "email", "");
		String verificationCodeMail = JsonTool.getStrValue(p, "verificationCodeMail", "");
		String checkCode = JsonTool.getStrValue(p, "checkcode", "");

		String userSetString = DicParamUtils.getParamValue(DicParamEnum.GLOBAL_OPERATION_USER_REGISTER.getVal());
		if (StrTool.isBlankStr(userSetString)) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_CRASH, "系统用户注册配置错误，无法完成注册，请联系管理员处理！");
		}
		JSONObject userSet = JSONObject.fromObject(userSetString);
		String forbid = userSet.getString("forbid");
		if (!StrTool.isBlankStr(forbid)) {
			String[] forbidArr = forbid.split("\n");
			for (String forbidItem : forbidArr) {
				if (userName.equals(forbidItem)) {
					return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "该账号名称已被禁止注册使用");
				}
			}
		}
		Boolean randCode = userSet.getBoolean("randCode");
		if (randCode && (StrTool.isBlankStr(checkCode) || !checkCode.toLowerCase().equals(CloudContextUtils.getSession().getCheckCode().toLowerCase()))) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "图片验证码错误");
		}

		JSONArray itemList = userSet.getJSONArray("registerItem");
		for (Object itemObject : itemList) {
			JSONObject item = (JSONObject) itemObject;
			String code = item.getString("code");
			Boolean must = item.getBoolean("must");
			Boolean auth = item.containsKey("auth") ? item.getBoolean("auth") : false;
			String name = item.getString("name");

			String checkAccount = "";
			String sessionCode = "";
			String userCode = "";
			if ("mobile".equals(code)) {
				checkAccount = mobile;
				sessionCode = SessionUtils.get(CConsts.CODE_AUTH_MOBILE_SESSION_NAME);
				userCode = verificationCodeMobile + "|" + checkAccount;
			} else if ("email".equals(code)) {
				checkAccount = email;
				sessionCode = SessionUtils.get(CConsts.CODE_AUTH_EMAIL_SESSION_NAME);
				userCode = verificationCodeMail + "|" + checkAccount;
			}

			if ((must || auth) && StrTool.isBlankStr(checkAccount)) {
				return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, name + "为必填");
			}

			if (auth && (StrTool.isBlankStr(userCode) || !userCode.toLowerCase().equals(sessionCode.toLowerCase()))) {
				return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, name + "认证码错误，或获取认证的" + name + "号不是当前" + name + "号");
			}
		}

		UserAccountUtils accountUtils = new UserAccountUtils();
		UserAccount account = accountUtils.isRegister(userName);
		if (null != account) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_EXISTS, "该账号已被其他用户关联注册");
		}
		if (!StrTool.isBlankStr(mobile)) {
			UserAccountView accountView = accountUtils.isRegisterMobile(mobile, 0);
			if (null != accountView) {
				return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_EXISTS, "该手机号已被其他用户关联注册");
			}
		}
		if (!StrTool.isBlankStr(email)) {
			UserAccount userAccount = accountUtils.isRegisterEmail(email);
			if (null != userAccount) {
				return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_EXISTS, "该邮箱已被其他用户关联注册");
			}
		}

		UserAccountUtils uaUtils = new UserAccountUtils();
		int rid = uaUtils.userRegister(userName, email, mobile, password, userType,true);
		//to refresh user account info for userId
		UserAccountView uv = null;
		if (rid>0) {
			uv = uaUtils.queryUserAccountView(rid);
		}
		String code = uaUtils.getErrCode();
		if ((rid<=0) || (uv==null)){
			return XmlCodeParser.formatResultTips(false, code, uaUtils.getMsg());
		}

		int uid = uv.getUserId();
		//自动分配客户和技术
		uaUtils.allotCrmAndCSST(uid);
//		SendResult mRet = SendMailUtils.sendActiveAccountMail(uid);
//
//		String jsRet = CJsonTool.beanToJson(mRet);
//		jsRet = CJsonTool.addNode(jsRet, "uid", uid);
//		if (mRet.getId() < 0){
//			return XmlCodeParser.formatCustomTips(false, mRet.getMsg(), jsRet);
//		}
//
//		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, jsRet);

		return  XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
	}

	/**
	 * resend active account email by user id, if user do not receive the active mail after registration,
	 * you can call this API to send active mail again
	 * @param req
	 * @param resp
	 * @param p = {"uid":userId}
	 * @param sid
	 * @return
	 */
	public String sendActiveAccountMail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CJsonTool.getIntValue(p, "uid", -1);
		if (uid<=0) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		//resend active email
		SendResult mRet = SendMailUtils.sendActiveAccountMail(uid);
		String jsRet = CJsonTool.beanToJson(mRet);
		jsRet = CJsonTool.addNode(jsRet, "uid", uid);
		if (mRet.getId()>0) {
			return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, jsRet);
		}

		return XmlCodeParser.formatResultData(true, SysErr.SYS_MAIL_SEND_ERR, jsRet);
	}

	/**
	 * to active user account
	 * @param req
	 * @param resp
	 * @param p={"uid":n,"code":"xxxxxxxxx"}
	 * @param sid
	 * @return
	 */
	public String activeAccount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CJsonTool.getIntValue(p, "uid", -1);
		String randomCode = CJsonTool.getStrValue(p, "code", "");
		if ((uid<=0) || (CStrTool.isBlankStr(randomCode))){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		UserAccountUtils uaUtils = new UserAccountUtils();
		boolean ret = uaUtils.activeUserAccount(uid, randomCode);
		String code = uaUtils.getErrCode();
		if (!ret) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return  XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
	}

	/**
	 * to verify user email
	 * @param req
	 * @param resp
	 * @param p={"QQ":"qq","address":"地址","certCode":"证件号码","certType":"证件类型","cityCode":"城市代码","companyName":"企业名",
	 * 			 "email":"邮箱","fax":"传真","fullName":"姓名","industry":"行业","mainBusiness":"主营业务","mobile":"手机",
	 * 			 "provinceCode":"省份代码","remark":"备注","tel":"联系电话","userType":n} userType=0 个人; userType=1企业;
	 * @param sid
	 * @return
	 */
	public String updateAccountDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String account = CSessionTool.getAccountCloud(sid);

		JSONObject j = CVerificationTool.StringToJsonObjectCV(p);
		if ((j==null) || Integer.parseInt(j.optString("userType"))<0 || Integer.parseInt(j.optString("userType"))>1){
			this.log(p+"->invalid UserAccountData json object");
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		j.put("certCode", EncryptUtils.decodeSession(j.getString("certCode")));

		ValidResult ret = CVerificationTool.verificationApi("updatePersonal", j);
		if(!ret.isSuccess()){
			return XmlCodeParser.formatCustomTips(false, ret.getMsg());
		}

		UserAccountDataUtils uadUtils = new UserAccountDataUtils();
		int retu = uadUtils.updateUserAccountData(account, j);
		boolean success = (retu>0);
		String code = uadUtils.getErrCode();
		return XmlCodeParser.formatResultTips(success, code);
	}

	/**
	 * 更新实名认证信息.
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String updateUserCert (HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		String fullName = JsonTool.getStrValue(p, "fullName", "");
		Integer certType = JsonTool.getIntValue(p, "certType", 1);
		String certCode = JsonTool.getStrValue(p, "certCode", "");
		String companyName = JsonTool.getStrValue(p, "companyName", "");
		Integer operation = JsonTool.getIntValue(p, "operation", 1);
		if (StrTool.isBlankStr(certCode) || 1 > certType || 2 < certType) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "参数错误1");
		}
		if (1 == certType && StrTool.isBlankStr(fullName)) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "参数错误2");
		}
		if (2 == certType && StrTool.isBlankStr(companyName)) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "参数错误3");
		}
		List<Object> certFile = new ArrayList<>();
		try {
			JSONObject idCardA = (JSONObject) CJsonTool.getValue(p, "idCardA");
			JSONObject idCardB = (JSONObject) CJsonTool.getValue(p, "idCardB");
			JSONObject enterprise = (JSONObject) CJsonTool.getValue(p, "enterprise");

			if (certType == 1) {
				if (!idCardA.containsKey("url") || !idCardB.containsKey("url")) {
					return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "参数错误4");
				}
				certFile.add(idCardA);
				certFile.add(idCardB);
			} else {
				if (!enterprise.containsKey("url")) {
					return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "参数错误5");
				}
				certFile.add(enterprise);
			}
		} catch (Exception e) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "参数错误6");
		}

		certCode = EncryptUtils.decodeSession(certCode);
		if (StrTool.isBlankStr(certCode)) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "参数错误7");
		}

		Map<String, Object> updateData = new HashedMap();
		if (1 == certType) {
			updateData.put("fullName", fullName);
		} else {
			updateData.put("companyName", companyName);
		}
		updateData.put("certType", certType);
		updateData.put("certCode", certCode);
		updateData.put("certFile", JSON.toJSONString(certFile));
		updateData.put("isCertified", 1 == operation ? UserCertifyEnum.NEVER.getState() : UserCertifyEnum.CERTIFYING.getState());
		Map<String, Object> where = new HashedMap();
		where.put("userId", CloudContextUtils.getSession().getUID());

		UserAccountDataUtils dataUtils = new UserAccountDataUtils();
		dataUtils.modifyAccountData(updateData, where);
		String code = dataUtils.getErrCode();
		if (code!=SysErr.CODE_SUCCESS) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
	}

	/**
	 * 实名审核.
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String updateUserCertCheck(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		Integer uid = JsonTool.getIntValue(p, "uid", 0);
		Integer state = JsonTool.getIntValue(p, "state", 0);
		String certifyDesc = JsonTool.getStrValue(p, "certifyDesc", "");
		if (uid<1 || state > 2 || state < 1) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		Map<String, Object> updateData = new HashedMap();
		if (1 == state) {
			updateData.put("isCertified", UserCertifyEnum.CERTIFIED.getState());
		} else {
			updateData.put("isCertified", UserCertifyEnum.REFUSED.getState());
		}
		updateData.put("certifyDesc", certifyDesc);
		Map<String, Object> where = new HashedMap();
		where.put("userId", uid);

		UserAccountDataUtils dataUtils = new UserAccountDataUtils();
		dataUtils.modifyAccountData(updateData, where);
		String code = dataUtils.getErrCode();
		if (code!=SysErr.CODE_SUCCESS) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		//操作日志

		return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
	}

	/**
	 * to verify user email
	 * @param req
	 * @param resp userlevel
	 * @param p={"uname":"用戶名","QQ":"qq","address":"地址","certCode":"证件号码","certType":"证件类型","cityCode":"城市代码","companyName":"企业名",
	 * 			 "email":"邮箱","fax":"传真","fullName":"姓名","industry":"行业","mainBusiness":"主营业务","mobile":"手机",
	 * 			 "provinceCode":"省份代码","remark":"备注","tel":"联系电话","userlevel":"用戶等级","userType":n} userType=0 个人; userType=1企业;
	 * @param sid
	 * @return
	 */
	public String updateAdminAccountDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		JSONObject j = CVerificationTool.StringToJsonObjectCV(p);
		String uname = CJsonTool.getStrValue(p, "uname", "");
		if ((j==null) || Integer.parseInt(j.optString("userType"))<0 || Integer.parseInt(j.optString("userType"))>1 || CStrTool.isBlankStr(uname)){
//			this.log(p+"->invalid UserAccountData json object");
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		ValidResult ret = CVerificationTool.verificationApi("updatePersonal", j);
		if(!ret.isSuccess()){
			return XmlCodeParser.formatCustomTips(false, ret.getMsg());
		}
		UserAccountDataUtils uadUtils = new UserAccountDataUtils();
		int retu = uadUtils.updateUserAccountData(uname, j);
		boolean success = (retu>0);
		String code = uadUtils.getErrCode();
		return XmlCodeParser.formatResultTips(success, code);
	}

	/**
	 * to update user account's password
	 * @param req
	 * @param resp
	 * @param p={"oldKey":"user old password","newKey":"new password"}
	 * @param sid
	 * @return
	 */
	public String updateAccountPassword(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String account = CSessionTool.getAccountCloud(sid);
		JSONObject j = CVerificationTool.StringToJsonObjectCV(p);
		ValidResult ret = CVerificationTool.verificationApi("updateAccountPwd", j);
		if(!ret.isSuccess()){
			return XmlCodeParser.formatCustomTips(false, ret.getMsg());
		}

		UserAccountUtils uaUtils = new UserAccountUtils();
		int retu = uaUtils.updateUserPassword(account, j.optString("oldKey"), j.optString("newKey"));
		boolean success = (retu>0);
		String code = uaUtils.getErrCode();

		if ( retu <= 0){
			return XmlCodeParser.formatResultTips(false, code);
		}
		int uid = CSessionTool.getUidCloud(sid);
		//发送确认邮件
		SendMailUtils.sendAccountModPassMail(uid);
		//发送确认短信
		SendSMSUtils.sendAccountModPassSMS(uid);

		return XmlCodeParser.formatResultTips(success, code);
	}

	/**
	 * 校验账号以及验证码
	 * @param req
	 * @param resp
	 * @param p={"email":"email address","checkcode":"xxxx"}
	 * @param sid
	 * @return
	 */
	public String sendFindPasswordMail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", null);
		String checkcode  = CJsonTool.getStrValue(p, "checkcode", null);
		if (CStrTool.isBlankStr(userName) || CStrTool.isBlankStr(checkcode)) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		//1 verify check code
		Session ssn = CSessionTool.getSessionCloud(sid);
		String ssncode = ssn.getCheckCode();
		if ((CStrTool.isBlankStr(checkcode)) || (!checkcode.toLowerCase().equals(ssncode.toLowerCase()))) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_CHECKCODE_ERR);
		}

		//2 to verify email->account exists
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccount u= uaUtils.queryAccountByName(userName);
		String err = uaUtils.getErrCode();
		if (err!=SysErr.CODE_SUCCESS) {
			return XmlCodeParser.formatResultTips(false, err);
		}
		if (u==null) {
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
		}

		UserAccountDataUtils uadUtils = new UserAccountDataUtils();
		UserAccountData userAccountData= uadUtils.queryAccountDataByName(userName);
		String code = uadUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			return XmlCodeParser.formatResultTips(false, code);
		}
		String email = "";
		String[] strarray=userAccountData.getEmail().split("@");
		if(strarray[0].length()>3){
			strarray[0] = strarray[0].substring(0,strarray[0].length()-3)+"***@";
			for(int i = 0;i<strarray.length;i++){
				email+=strarray[i];
			}
		}else{
			email +=userAccountData.getEmail();
		}
		String data = String.format("{\"email\":%s}", "'"+email+"'");
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
	}

	/**
	 * 发送邮件激活码
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String MailValidate(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		if(CStrTool.isBlankStr(userName)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		//1.验证账号是否存在
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccount u= uaUtils.queryAccountByName(userName);
		String err = uaUtils.getErrCode();

		//2.更新randomCode
		if (err!=SysErr.CODE_SUCCESS){
			return XmlCodeParser.formatResultTips(false, err);
		}
		if (u==null){
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
		}
		String RndPwd = CSysTool.GetRndPwd(8);
		uaUtils.uptAccountByCode(userName, RndPwd);

		//3.获取userAccount的具体数据（邮箱手机号）
		UserAccountDataUtils uadUtils = new UserAccountDataUtils();
		UserAccountData  userAccountData= uadUtils.queryAccountDataByName(userName);
		String code = uadUtils.getErrCode();
		if (code!=SysErr.CODE_SUCCESS) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		//优化会员名
		String tempName=u.getUserName().subSequence(0, 1)+"***"+u.getUserName().substring(u.getUserName().length()-1);

		//发送激活码给邮箱
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("\\[账户名\\]", tempName));
		params.add(new BasicNameValuePair("\\[验证码\\]", RndPwd));
		SendMailUtils.sendNotifyMail("findPwdCodeEmail", userAccountData.getEmail(), params);
		return XmlCodeParser.formatResultTips(true,SysErr.CODE_SUCCESS);
	}

	/**
	 * 邮箱激活码验证
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String verifyMail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		String checkcode = CJsonTool.getStrValue(p, "checkcode", "");
		if(CStrTool.isBlankStr(userName)||CStrTool.isBlankStr(checkcode)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		//1.验证账号是否存在
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccount u= uaUtils.queryAccountByName(userName);
		UserAccount queryUserNameAndCode = uaUtils.queryUserNameAndCode(userName, checkcode);
		String err = uaUtils.getErrCode();
		if (err!=SysErr.CODE_SUCCESS) {
			return XmlCodeParser.formatResultTips(false, err);
		}
		if (u==null) {
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
		}
		if(queryUserNameAndCode==null) {
			return XmlCodeParser.formatResultTips(false, AppCode.RANDOMCODE_ERROR);
		}
		return XmlCodeParser.formatResultTips(true,SysErr.CODE_SUCCESS);
	}

	/**
	 * 修改密码
	 * @param req
	 * @param resp
	 * @param p={"userName":"用户名","password":"新密码","checkcode","激活码"}
	 * @param sid
	 * @return
	 */
	public String resetPassword(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		JSONObject j = CVerificationTool.StringToJsonObjectCV(p);
		ValidResult ret = CVerificationTool.verificationApi("retrievepwd", j);
		if(!ret.isSuccess()){
			return XmlCodeParser.formatCustomTips(false, ret.getMsg());
		}
		//to verify user exists and random code is right
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccount u = uaUtils.queryAccountByName(j.optString("userName"));
		UserAccount queryUserNameAndCode = uaUtils.queryUserNameAndCode(j.optString("userName"), j.optString("checkcode"));
		String err = uaUtils.getErrCode();
		if (err!=SysErr.CODE_SUCCESS){
			return XmlCodeParser.formatResultTips(false, err);
		}
		if (u==null){
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
		}
		if(queryUserNameAndCode==null){
			return XmlCodeParser.formatResultTips(false, AppCode.RANDOMCODE_ERROR);
		}
		//reset user password by user name
		int retu = uaUtils.resetUserPassword(u.getUserName(), j.optString("password"));
		err = uaUtils.getErrCode();
		if(retu>0){
			//发送重置成功邮件和短信
			SendMailUtils.sendAccountModPassMail(u.getUserId());
			SendSMSUtils.sendAccountModPassSMS(u.getUserId());
		}

		return XmlCodeParser.formatResultTips(retu>0, err);
	}

	/**
	 * to get current login user account detail info
	 * @param req
	 * @param resp
	 * @param p=null
	 * @param sid
	 * @return
	 */
	public String getAccountDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccountView uv = uaUtils.queryUserAccountViewByUid(uid);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			return XmlCodeParser.formatResultTips(false, code);
		}
		if (uv==null){
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
		}
		if (!StrTool.isBlankStr(uv.getMobile())) {
			uv.setMobileEncode(EncryptUtils.encodeSession(uv.getMobile()));
			uv.setMobile(ProtectionStartUtils.mobile(uv.getMobile()));
		}
		String starCertCard = ProtectionStartUtils.idCard(uv.getCertCode());
		if (!StrTool.isBlankStr(uv.getCertCode())) {
			uv.setCertCode(EncryptUtils.encodeSession(uv.getCertCode()));
		}
		String data = formatUserAccountView(uv);
		JsonTool.addNode(data, "certCodeStar", starCertCard);
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
	}

	/**
	 * to query user account info
	 * @param req
	 * @param resp
	 * @param p={"account":"account","email":"xxx@xxx.yy","mobile":"xxxxxxxxxxx","page":pageindex,"pagesize":n}
	 * @param sid
	 * @return
	 */
	public String queryAccount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String act   = CJsonTool.getStrValue(p, "account", null);
		String email = CJsonTool.getStrValue(p, "email", "");
		String mobile= CJsonTool.getStrValue(p, "mobile", "");
		String levelCode= CJsonTool.getStrValue(p, "levelCode", "");
		Integer certify = JsonTool.getIntValue(p, "certify", -1);
		int page     = CJsonTool.getIntValue(p, "page", 1);
		int pagesize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);

		String bstartTime = JsonTool.getStrValue(p, "bstartTime", "");
		String bendDate = JsonTool.getStrValue(p, "bendDate", "");
		//to query rows count with condition
		UserAccountUtils uaUtils = new UserAccountUtils();
		int rows = uaUtils.queryUserAccountView(act, email, mobile, levelCode, bstartTime, bendDate);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			return XmlCodeParser.formatResultTips(false,code);
		}
		if (rows<(page-1)*pagesize){
			return XmlCodeParser.formatResultData(true, code, "[]");
//			return XmlCodeParser.formatResultTips(true,SysErr.SYS_DATA_NOT_FOUND);
		}
		int pages = Math.round((rows+pagesize-1)/pagesize);
		//to query rows record
		List<UserAccountView> users = uaUtils.queryUserAccountView(act, email, mobile,levelCode, certify, bstartTime, bendDate, page, pagesize);
		code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			return XmlCodeParser.formatResultTips(false, code);
		}
		if (users.size()<=0){
			return XmlCodeParser.formatResultData(true, code, CJsonTool.listBeanToJson(users));
		}

		//data to json
		String data = "[";
		String row;
		for(UserAccountView u: users){
			if (!StrTool.isBlankStr(u.getMobile())) {
				u.setMobile(EncryptUtils.encodeSession(u.getMobile()));
			}
			if (!StrTool.isBlankStr(u.getCertCode())) {
				u.setCertCode(EncryptUtils.encodeSession(u.getCertCode()));
			}
			u.setCertifyName(UserCertifyEnum.getStateName(u.getIsCertified()));

			row = this.formatUserAccountView(u);
			data = data+row+",";
		}
		if (users.size()>0) {
			data = CStrTool.deleteCharAt(data, data.length()-1);
		}
		data = data+"]";
		return XmlCodeParser.formatResultPageData(code, page, pages, pagesize, rows, data);
	}

	/**
	 * 管理员获取会员信息列表
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String qryAccountList(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String act   = CJsonTool.getStrValue(p, "account", null);
		int page     = CJsonTool.getIntValue(p, "page", 1);
		int pagesize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);
		//to query rows count with condition
		Map<String, Object> cdt = new HashMap<String, Object>();
		if(!StrTool.isBlankStr(act)){
			cdt.put("a.userName", act);
		}
		UserAccountUtils uaUtils = new UserAccountUtils();
		int rows = uaUtils.queryUserAccountView(cdt);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			return XmlCodeParser.formatResultTips(false,code);
		}
		if (rows<(page-1)*pagesize){
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_DATA_NOT_FOUND);
		}
		int pages = Math.round((rows+pagesize-1)/pagesize);
		//to query rows record
		List<UserAccountView> users = uaUtils.queryUserAccountView(cdt, page, pagesize);
		code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			return XmlCodeParser.formatResultTips(false, code);
		}
		if (users.size()<=0){
			return XmlCodeParser.formatResultData(true, code, CJsonTool.listBeanToJson(users));
		}

		//data to json
		String data = "[";
		String row;
		for(UserAccountView u: users){
			if (!StrTool.isBlankStr(u.getMobile())) {
				u.setMobile(EncryptUtils.encodeSession(u.getMobile()));
			}
			if (!StrTool.isBlankStr(u.getCertCode())) {
				u.setCertCode(EncryptUtils.encodeSession(u.getCertCode()));
			}
			u.setCertifyName(UserCertifyEnum.getStateName(u.getIsCertified()));

			if (!u.getAgentId().equals(CloudContextUtils.getAgentId())) {
				u.setIsOwn(0);
			}

			row = this.formatUserAccountView(u);
			data = data+row+",";
		}
		if (users.size()>0) {
			data = CStrTool.deleteCharAt(data, data.length()-1);
		}
		data = data+"]";
		return XmlCodeParser.formatResultPageData(code, page, pages, pagesize, rows, data);
	}


	/**
	 * to get user account detail for admin
	 * @param req HttpServletRequest parameter
	 * @param resp HttpServletResponse parameter
	 * @param p={"rid":n}
	 * @param sid session id
	 * @return json string
	 */
	public String getUserDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int rid = CJsonTool.getIntValue(p, "rid", -1);
		if (rid<=0){
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_PARAM_ERR);
		}
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccountView uv = uaUtils.queryUserAccountView(rid);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		if (uv==null) {
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
		}

		if (!StrTool.isBlankStr(uv.getMobile())) {
			uv.setMobile(EncryptUtils.encodeSession(uv.getMobile()));
		}
		if (!StrTool.isBlankStr(uv.getCertCode())) {
			uv.setCertCode(EncryptUtils.encodeSession(uv.getCertCode()));
		}

		if (!uv.getAgentId().equals(CloudContextUtils.getAgentId())) {
			uv.setIsOwn(0);
		}

		String data = formatUserAccountView(uv);
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
	}

	/**
	 * 根据userName与UserId删除会员
	 * @param req
	 * @param resp
	 * @param p={"userName":"userName","userId":userId}
	 * @param sid
	 * @return
	 */
	public String deleteAccount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		int userId = CJsonTool.getIntValue(p, "userId", -1);

		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccountDataUtils uadUtils = new UserAccountDataUtils();
		int ret = uaUtils.deleteUserAccountByUserNameAndUserId(userId, userName);
		String code = uaUtils.getErrCode();
		uadUtils.deleteAccountByUserName(userName);
		String code1 = uadUtils.getErrCode();
		if (!code1.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 后台添加用户
	 * @param req
	 * @param resp
	 * @param p={"userName":"userName","password":"password","email":"email","moblie":"moblie"}
	 * @param sid
	 * @return
	 */
	public String addUserAccount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		String password = CJsonTool.getStrValue(p, "password", "");
		String email  = CJsonTool.getStrValue(p, "email", "");
		String mobile = CJsonTool.getStrValue(p, "moblie", "");
		if (CStrTool.isBlankStr(userName) || CStrTool.isBlankStr(email) || CStrTool.isBlankStr(mobile) ||
			CStrTool.isBlankStr(password)){
			this.log(p+"-->invalid new user account parameter");
			return XmlCodeParser.formatResultTips(false, SysErr.USER_EXISTS);
		}
		UserAccountUtils uaUtils = new UserAccountUtils();
		//判断账号是否唯一
		if(uaUtils.queryAccountByName(userName) != null){
			return XmlCodeParser.formatResultTips(false,SysErr.USER_EXISTS);
		}

		UserAccountDataUtils uadUtils = new UserAccountDataUtils();
		//判断电话是否唯一
		if(uadUtils.queryAccountDataByMobile(mobile) != null){
			return XmlCodeParser.formatResultTips(false,AppCode.MOBILE_EMPTY);
		}

		//判断邮箱是否唯一
		if(uadUtils.queryAccountDataByEmail(email) != null){
			return XmlCodeParser.formatResultTips(false,AppCode.EMAIL_EXISTS);
		}

		int rid = uaUtils.userRegister(userName, email, mobile, password, 0);
		int ret = uaUtils.uptUserAccountState(userName, rid);
		String code2 = uaUtils.getErrCode();
		return XmlCodeParser.formatResultTips(ret>0, code2);
	}

	/**
	 * 后台修改用户状态
	 * @param req
	 * @param resp
	 * @param p={"userName":"userName","userId":"userId","status":"status"}
	 * @param sid
	 * @return
	 * @author 830
	 */
	public String uptAccountState(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		int rid = CJsonTool.getIntValue(p, "userId", -1);
		String status = CJsonTool.getStrValue(p, "status", "");

		UserAccountUtils uaUtils = new UserAccountUtils();
		int ret = uaUtils.uptUserAccountState(userName, rid, status);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 后台修改用户等级
	 * @param req
	 * @param resp
	 * @param p={"userName":"userName","levelCode":"levelCode"}
	 * @param sid
	 * @return
	 * @author 830
	 */
	public String uptAccountLevel(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();

		String userName = CJsonTool.getStrValue(p, "userName", "");
		String levelCode = CJsonTool.getStrValue(p, "levelCode", "");
		UserAccountUtils uaUtils = new UserAccountUtils();
		int ret = uaUtils.uptAccountLevel(uid,userName,levelCode);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 统计会员
	 * @param req
	 * @param resp
	 * @param p={"day":"时间数"} 0 当天注册  7天内注册
	 * @param sid
	 * @return
	 * @author 830
	 */
	public String getAccountCount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int day = CJsonTool.getIntValue(p, "day", 0);
		Map<String, Object> map = new HashMap<String, Object>();
		if(day > 0){
			map.put("start", CDateTimeTool.dateToDateString(CDateTimeTool.incDay(new Date(), -day)));
		}else{
			map.put("start", CDateTimeTool.dateToDateString(new Date()));
		}
		map.put("end", CDateTimeTool.dateToDateString(CDateTimeTool.incDay(new Date(), 1)));
		UserAccountUtils uaUtils = new UserAccountUtils();
		int ret = uaUtils.getUserAccount(map);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultData(true, code,"\""+ret+"\"");
	}

	/**
	 * 修改后台管理员密码
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String uptadminpas(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String oldPassword = CJsonTool.getStrValue(p, "oldPassword", "");
		String newPassword = CJsonTool.getStrValue(p, "newPassword", "");
		if(CStrTool.isBlankStr(oldPassword)||CStrTool.isBlankStr(newPassword)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		oldPassword = EncryptUtils.decodeSession(oldPassword);
		newPassword = EncryptUtils.decodeSession(newPassword);
		if(CStrTool.isBlankStr(oldPassword)||CStrTool.isBlankStr(newPassword)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		CUserUtils cUserUtils = new CUserUtils();
		User user = cUserUtils.queryPassword(CSessionTool.getAccountCloud(sid), oldPassword);
		if(user==null){
			return XmlCodeParser.formatResultTips(false, SysErr.USER_OLD_PASSWORD_ERR);
		}
		int ret = cUserUtils.uptadminpas(CSessionTool.getAccountCloud(sid), newPassword);
		String code = cUserUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 重置密码(随机生成)
	 * @param req
	 * @param resp
	 * @param p={"id":id}
	 * @param sid
	 * @return
	 */
	public String adminResetPwd(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String username = CJsonTool.getStrValue(p, "username", "");
		if(CStrTool.isBlankStr(username)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		String newPassword = CSysTool.GetRndPwd(8);
		UserAccountUtils uaUtils = new UserAccountUtils();
		int ret = uaUtils.resetUserPassword(username, newPassword);
		String code = uaUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		if(ret<=0){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		String data = "{\"password\":\""+newPassword+"\"}";
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
	}

	public String authThirdLogin(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String openId = CJsonTool.getStrValue(p, "openId", "");
		Integer loginType = CJsonTool.getIntValue(p, "loginType", -1);
		if(CStrTool.isBlankStr(openId) || loginType <= -1){
			return XmlCodeParser.formatResultTips(true, SysErr.SYS_PARAM_ERR);
		}
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccountView accountView = uaUtils.qryUserAccountViewByOpenId(openId);
		//进行openId判断是否已注册，未注册进行第三登录账号创建
		if(accountView == null){
			return XmlCodeParser.formatResultTips(true, SysErr.USER_NOT_EXISTS);
		}
		UserAccount	userAccount = uaUtils.queryUserAccountById(accountView.getId());
		String data = dealSetLoginCookie(userAccount,sid,req,resp);
		return XmlCodeParser.formatResultData(true, "S000", data);
	}

	public String bindingThirdAuthAccount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		Integer loginType = JsonTool.getIntValue(p,"loginType",-1);
		//1.存在账号绑定  2.不存在重新注册生成绑定
		Integer type = JsonTool.getIntValue(p,"type",-1);
		String openId = JsonTool.getStrValue(p,"openId","");
		String userName = JsonTool.getStrValue(p,"userName","");
		String password = JsonTool.getStrValue(p,"password","");
		Integer userType = JsonTool.getIntValue(p,"userType",-1);
		String mobile = JsonTool.getStrValue(p,"mobile","");
		String email = JsonTool.getStrValue(p,"email","");
		if(CStrTool.isBlankStr(openId) || CStrTool.isBlankStr(userName) || type <= -1){
			return XmlCodeParser.formatResultTips(true, SysErr.SYS_PARAM_ERR);
		}
		int ret = 0;
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccount userAccount = null;
		if(type == 2){
			if(CStrTool.isBlankStr(password)){
				return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
			}
			ret = uaUtils.userRegister(userName, email,mobile, password,userType,true,openId,loginType);
			//to refresh user account info for userId
			userAccount = uaUtils.queryUserAccountById(ret);
		}else{
			//账号不存在
			userAccount = uaUtils.isRegister(userName);
			if(userAccount == null){
				return XmlCodeParser.formatResultTips(true, SysErr.USER_NOT_EXISTS);
			}
			ret = uaUtils.uptAccountOpenIdByuserId(userAccount.getUserId(),openId,loginType);
		}
		if(ret <= 0){
			return XmlCodeParser.formatResultTips(true, SysErr.USER_LOGIN_EXPIRY);
		}
		String data = dealSetLoginCookie(userAccount,sid,req,resp);
		return XmlCodeParser.formatResultData(true, "S000", data);

	}

	public String dealSetLoginCookie(UserAccount userAccount,String sid,HttpServletRequest req, HttpServletResponse resp){
		UserAccountUtils uaUtils = new UserAccountUtils();
		int uid = userAccount.getUserId();
		Session ssn = new Session();
		ssn.setId(userAccount.getId());
		ssn.setUID(uid);
		ssn.setUname(userAccount.getUserName());
		//set user account email
		UserAccountView v = uaUtils.queryUserAccountView(userAccount.getId());
		ssn.setData(v.toJsonString());
		ssn.setUtype(1);
		//TODO to fill user functions
		ssn.setFuncs("");
		CSessionTool.setLoginSessionCloud(sid, ssn);
		//set user cookie,it contains: account id\account
		Cookies cks = new Cookies();
		cks.setId(userAccount.getId());
		cks.setUid(uid);
		cks.setAccount(userAccount.getUserName());
		cks.setUname(userAccount.getUserName());
		cks.setSaid(CEncryptTool.encodeSAID(sid, uid, userAccount.getUserName()));
		CookieTool.setLoginCookie(resp, sid, cks);

		EncryptUtils.makeSession(resp, req);

		//自动修复分配客服和技术
		uaUtils.allotCrmAndCSST(uid);

		UserLogUtils.addLog("user.login", userAccount.getUserId(), "用户登录成功");

		String data = CJsonTool.beanToJson(userAccount);
		data = CJsonTool.delNode(data, "passWord");
		data = CJsonTool.delNode(data, "regTime");
		data = CJsonTool.delNode(data, "randomCode");
		data = CJsonTool.addNode(data, "regTime", CDateTimeTool.dateToDateString(userAccount.getRegTime()));
		return data;
	}

}